﻿using JESAI.DistributedLock.Redis.RedLock;
using StackExchange.Redis;
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace JESAI.DistributedLock.Redis.Primitives;

internal class RedisScript<TArgument>(string script, Func<TArgument, object> parameters)
{
    private readonly LuaScript _script = LuaScript.Prepare(RemoveExtraneousWhitespace(script));

    public RedisResult Execute(IDatabase database, TArgument argument, bool fireAndForget = false) =>
        // 数据库。必须调用ScriptEvaluate而不是脚本。评估以尊重数据库的键前缀
        database.ScriptEvaluate(this._script, parameters(argument), flags: RedLockHelper.GetCommandFlags(fireAndForget));

    public Task<RedisResult> ExecuteAsync(IDatabaseAsync database, TArgument argument, bool fireAndForget = false) =>
        // 数据库。必须调用ScriptEvaluate而不是脚本。评估以尊重数据库的键前缀
        database.ScriptEvaluateAsync(this._script, parameters(argument), flags: RedLockHelper.GetCommandFlags(fireAndForget));

    // 将尽可能小的脚本发送到服务器
    private static string RemoveExtraneousWhitespace(string script) => Regex.Replace(script.Trim(), @"\s+", " ");
}
